<template>
  <div class="login-content">
    <div class="login-card">
      <div class="card-body">
        <div class="login-index" v-loading="loading" element-loading-text="系统加载中..." :fullscreen="true">
          <!-- 顶部注册账号 -->
          <router-link class="register-link" to="/login/register">
            <span class="link-btn">注册</span>
          </router-link>
          <div class="login-container">
            <!-- 左侧二维码区域 -->
            <div v-if="loginSetting.useQrCode" class="qrcode-section hide-on-mobile" ref="qrcodeRef">
              <div v-loading="qrLoading" class="qrcode-box">
                <div v-if="loginSetting.mode !== 2" class="qrcode-title" v-html="loginSetting.name"></div>
                <div id="qrcode-container"></div>
                <div class="qrcode-info">请使用微信扫描二维码登录</div>
              </div>
            </div>

            <!-- 右侧登录表单区域 -->
            <div class="form-section" :class="loginSetting.useQrCode ? 'qrcode-padding' : ''">
              <template v-if="showReset">
                <LoginReset @back="showReset = false" @success="handleResetSuccess" />
              </template>
              <div v-else class="form-content">
                <div class="form__span_box">
                  <span class="form__span switch-btn" :class="!formFlag ? 'cur_form' : ''" @click="handleChangeForm('phone')">账号密码登录</span>
                  <span class="form__span switch-btn" :class="formFlag ? 'cur_form' : ''" @click="handleChangeForm('psd')">手机号登录</span>
                </div>

                <div class="form-box">
                  <!-- 账号密码登录 -->
                  <el-form class="login-form" v-if="!formFlag" :model="userForm" :rules="userFormRules" ref="userFormRef" size="large">
                    <el-form-item prop="account">
                      <el-input type="text" placeholder="请输入账号名" v-model="userForm.account" autocomplete="off" />
                    </el-form-item>
                    <el-form-item prop="password">
                      <el-input type="password" placeholder="请输入登录密码" v-model="userForm.password" autocomplete="off" show-password />
                    </el-form-item>
                    <SlideVerify @onSuccess="handleLogin" v-model:show="loginVerifyShow" />
                    <el-form-item>
                      <el-button class="login-btn" type="primary" @click="beforeLogin" :loading="loginLoading">登录</el-button>
                    </el-form-item>
                  </el-form>

                  <!-- 手机号登录 -->
                  <el-form class="login-form" v-else :model="phoneForm" :rules="phoneFormRules" ref="phoneFormRef" size="large">
                    <el-form-item prop="phoneNumber">
                      <el-input type="text" placeholder="请输入手机号" v-model="phoneForm.phoneNumber" />
                    </el-form-item>
                    <el-form-item prop="authCode">
                      <GetVarCode v-model="phoneForm.authCode" :phone="phoneForm.phoneNumber" />
                    </el-form-item>
                    <el-form-item>
                      <el-button class="login-btn" type="primary" @click="handleLogin" :loading="loginLoading">登录</el-button>
                    </el-form-item>
                  </el-form>
                </div>

                <div v-if="!formFlag" class="forget-pass-btn">
                  <router-link class="form__link" to="/login/forget">找回密码</router-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
/* eslint-disable */
import { ElMessage } from 'element-plus'
import { ref, reactive, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import LoginReset from './Reset.vue'
import GetVarCode from './components/GetVarCode.vue'

const router = useRouter()
const route = useRoute()
const store = useStore()
const loading = ref(false)
const loginSetting = computed(() => store.state.site.loginSetting)
//账户密码登录
const userFormRef = ref(null)
const userFormRules = reactive({
  account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
const userForm = ref({
  account: '',
  password: ''
})
//手机验证码登录
const phoneFormRef = ref(null)
// 手机号校验
const phoneValid = async (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入手机号'))
  }
  if (!/^1[3456789]\d{9}$/.test(value)) {
    return callback(new Error('请输入正确的手机号'))
  }
  callback()
}

const phoneFormRules = reactive({
  phoneNumber: [{ validator: phoneValid, trigger: 'blur' }],
  authCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})
const phoneForm = ref({
  phoneNumber: '',
  authCode: ''
})
// 监听路由重定向参数 redirect: 重定向地址
const _redirect = ref(undefined)
const _hash = ref(undefined)
const _query = ref(undefined)
watch(
  () => router.currentRoute.value,
  route => {
    // eslint-disable-next-line no-unused-vars
    let { redirect, code, ...query } = route.query
    _redirect.value = redirect
    _hash.value = route.hash

    _query.value = query
  },
  { immediate: true }
)

//登录（需准备授权信息带入授权页面）
const loginLoading = ref(false)
const loginVerifyShow = ref(false)
const beforeLogin = () => {
  let curForm
  if (!formFlag.value) {
    // 账号登录
    curForm = userFormRef.value
  } else {
    curForm = phoneFormRef.value
  }
  curForm.validate( valid => {
    if (!valid) return
    loginVerifyShow.value = true
  })
}
const handleLogin = () => {
  let curForm, curApi, curParams
  if (!formFlag.value) {
    // 账号登录
    curForm = userFormRef.value
    curApi = 'user/loginByAccount'
    curParams = userForm.value
  } else {
    curForm = phoneFormRef.value
    curApi = 'user/loginByPhone'
    curParams = phoneForm.value
  }
  curForm.validate(async valid => {
    loginLoading.value = true
    if (valid) {
      let res = await store.dispatch(curApi, curParams).finally(() => {
        loginLoading.value = false
      })
      if (!res) {
        showReset.value = true
        return
      }
      afterLogin(res)
    } else {
      loginLoading.value = false
    }
  })
}

const afterLogin = res => {
  if (res && res.code === 20000) {
    ElMessage({
      showClose: true,
      message: '登录成功！',
      type: 'success'
    })
    // 如果有回调地址，则跳转到回调地址，否则进入导航页面
    // if (route.query.redirect) {
    //   window.location.reload()
    // }else {
    // router.push('/home')

    router.push({ path: _redirect.value + _hash.value || '/', query: _query.value })
    // }
  }
}

const qrLoading = ref(false)
const wechatQrcode = computed(() => store.state.site.wechatQrcode)
const qrcodeRef = ref(null)
const handleWechat = async () => {
  qrLoading.value = true
  // 提取wechatQrcode地址中的参数
  const url = new URL(wechatQrcode.value)
  const params = new URLSearchParams(url.search)
  const appid = params.get('appid')
  const state = params.get('state')
  const redirect_uri = params.get('redirect_uri')

  try {
    let option = {
      id: 'qrcode-container',
      appid,
      redirect_uri,
      state,
      scope: 'snsapi_login',
      stylelite: 1
    }
    // eslint-disable-next-line
    new WxLogin(option)
  } catch (error) {
    console.error('获取二维码失败:', error)
  } finally {
    qrLoading.value = false
  }
}
watch([wechatQrcode, qrcodeRef], (newVal) => {
  if (newVal[0] && newVal[1]) {
    handleWechat()
  }
}, { deep: true })

const formFlag = ref(false)
const handleChangeForm = () => {
  formFlag.value = !formFlag.value
}

const showReset = ref(false)
const handleResetSuccess = () => {
  showReset.value = false
  ElMessage.success('密码重置成功，请重新登录')
}
</script>

<style lang="scss" scoped>
.login-content {
  height: 100%;
  display: grid;
  place-items: center;
  z-index: 1;

  .login-card {
    position: relative;
    padding: 30px 20px 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    background: #fff;
    display: flex;
    flex-direction: column;
    z-index: 1;

    .card-body {
      flex: 1;
      overflow: hidden;
    }
  }
}

.login-index {
  min-height: 339px;
  height: 100%;
  overflow: hidden;

  .register-link {
    cursor: pointer;
    height: 70px;
    width: 70px;
    background-image: linear-gradient(to right bottom, rgb(186, 172, 255), rgb(48, 128, 255));
    clip-path: polygon(0% 0%, 100% 0%, 100% 100%);
    position: absolute;
    top: 0px;
    right: 0px;
    text-align: right;
    z-index: 2;

    .link-btn {
      font-size: 14px;
      color: #fff;
      font-weight: 500;
      position: relative;
      top: 10px;
      right: 7px;
    }
  }

  .login-container {
    display: flex;
    height: 100%;
    position: relative;
    z-index: 1;
    
    @media screen and (max-width: 768px) {
      justify-content: center;
      padding: 0 20px;
    }

    .qrcode-section {
      padding: 60px 70px 60px 50px;
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 300px;
      box-sizing: border-box;
      border-right: 1px solid #e5e5e5;
      background: rgba(255, 255, 255, 0.9);

      &.hide-on-mobile {
        @media screen and (max-width: 768px) {
          display: none;
        }
      }

      .qrcode-box {
        text-align: center;

        .qrcode-title {
          font-size: 16px;
          color: #333;
          margin-bottom: 20px;
        }

        .qrcode-info {
          font-size: 14px;
          color: #999;
          margin-top: 20px;
        }
      }
    }

    .form-section {
      position: relative;
      width: 440px;
      box-sizing: border-box;
      background: rgba(255, 255, 255, 0.9);
      
      &.qrcode-padding {
        padding-left: 50px;
      }

      @media screen and (max-width: 768px) {
        padding-left: 0;
        width: 100%;
        max-width: 440px;
      }

      .form-content {
        padding-top: 20px;

        .form__span_box {
          margin-bottom: 30px;
          display: flex;
          gap: 40px;

          .form__span {
            font-size: 16px;
            color: #666;
            cursor: pointer;
            padding-bottom: 8px;
            border-bottom: 2px solid transparent;

            &.cur_form {
              color: var(--el-color-primary);
              border-bottom-color: var(--el-color-primary);
            }
          }
        }

        .form-box {
          .login-form {
            .login-btn {
              height: 50px;
              width: 100%;
              font-size: 16px;
            }

            :deep(.el-form-item) {
              margin-bottom: 20px;
              
              .el-input {
                --el-input-height: 50px;
              }
            }
          }
        }

        .forget-pass-btn {
          text-align: right;
          margin-top: 16px;
          
          .form__link {
            color: #666;
            text-decoration: none;
            font-size: 14px;
            
            &:hover {
              color: var(--el-color-primary);
            }
          }
        }
      }
    }
  }
}

:deep(.el-form-item__error:before) {
  display: none !important;
}
</style>